<template>
  <div class="projectRoleListContainer" v-loading="loading">
    <div class="text">角色权限</div>
    <div class="roleList">
      <div
        v-for="(item, index) in roleList"
        :key="item.id"
        class="roleItem"
        :style="{
          background: currentIndex === index ? '#e6f3fc' : '',
          color: currentIndex === index ? '#1AA1FB' : '#1D2129',
          cursor: item.isManager === 'YES' ? 'not-allowed' : 'pointer',
        }"
        @click="handleSelectRole(item, index)"
      >
        <img class="avatar" src="@/assets/pm/roleAvatar.svg" />
        <span class="roleName">{{ item?.name?.zh_CN }}</span>
        <el-popover
          v-if="item.isManager !== 'YES'"
          popper-class="customPopoverClass"
          :show-arrow="false"
          placement="bottom-end"
        >
          <template #reference>
            <span class="moreSpan">
              <el-icon size="14" color="#707070">
                <MoreFilled />
              </el-icon>
            </span>
          </template>
          <template #default>
            <div class="nodeMorePopoverClass">
              <ul class="popoverList">
                <li @click="handleEdit(item, index)" class="popoverItem">
                  <img src="@/assets/pm/edit.svg" />重命名
                </li>
                <li
                  style="color: #d54941"
                  @click="handleDel(item, index)"
                  class="popoverItem"
                >
                  <img src="@/assets/lifecycle/delete.svg" />删除
                </li>
              </ul>
            </div>
          </template>
        </el-popover>
      </div>
      <div @click="handleAddRole" class="roleItem">
        <img class="avatar" src="@/assets/pm/add.svg" />
        <span class="roleName">添加角色</span>
      </div>
    </div>
    <CDialog
      :title="operate === 'create' ? '新建' : '编辑'"
      v-model="dialogVisible"
      @handleDialogOk="handleCreateOrEdit"
      :fields="dialogFields"
      :nodeData="selectedNode"
    ></CDialog>
  </div>
</template>
<script setup lang="ts">
  import { MoreFilled } from "@element-plus/icons-vue";
  import { ElMessage, ElMessageBox } from "element-plus";
  import { onMounted, ref, watch } from "vue";
  import {
    getProjectRoleList,
    deleteProjectRole,
    createProjectRole,
    editProjectRole,
  } from "@/api/pm/projectRole.ts";
  import type { projectRoleVo } from "@/interface/pm/projectRole.ts";
  import CDialog from "@/components/CDialog.vue";
  import type { DynamicField } from "@/data/wbsFields.ts";
  import { deepCopy } from "@/utils/common.ts";
  interface Props {
    projectId: string;
  }
  interface Emits {
    getRolePermission: [item: projectRoleVo];
  }
  const emits = defineEmits<Emits>();
  const dialogFields: DynamicField[] = [
    {
      id: 1,
      field: "id",
      type: "text",
      invisible: false,
      name: "id",
    },
    {
      id: 2,
      field: "name",
      type: "text",
      invisible: true,
      name: "角色名称",
      rules: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
    },
  ];
  const currentIndex = ref(-1);
  const currentEditIndex = ref(-1);
  watch(
    currentIndex,
    () => {
      console.log(
        "触发",
        currentIndex.value,
        roleList.value[currentIndex.value],
      );
      if (roleList.value[currentIndex.value]) {
        emits("getRolePermission", roleList.value[currentIndex.value]!);
      }
    },
    { immediate: false },
  );
  const operate = ref("create");
  const dialogVisible = ref(false);
  const selectedNode = ref<projectRoleVo>({} as projectRoleVo);
  const loading = ref(false);
  const roleList = ref<projectRoleVo[]>([]);
  const props = defineProps<Props>();
  const getList = async () => {
    loading.value = true;
    const res = await getProjectRoleList({
      pageSize: 500,
      pageNo: 1,
      conditions: [
        {
          field: "projectId",
          value: props.projectId,
          operator: "like",
        },
      ],
    });
    loading.value = false;
    roleList.value = res.result || [];
    if (roleList.value.length > 0 && currentIndex.value === -1) {
      currentIndex.value = 0;
    }
    if (
      (currentIndex.value !== -1 &&
        currentIndex.value === currentEditIndex.value) ||
      roleList.value.length === 0
    ) {
      emits("getRolePermission", roleList.value[currentIndex.value]);
    }
  };
  const handleSelectRole = (item: projectRoleVo, index: number) => {
    currentIndex.value = index;
  };
  const handleEdit = (item: projectRoleVo, index: number) => {
    operate.value = "edit";
    currentEditIndex.value = index;
    selectedNode.value = deepCopy(item);
    selectedNode.value.name = item.name.zh_CN;

    dialogVisible.value = true;
  };
  const handleDel = (item: projectRoleVo, index: number) => {
    ElMessageBox.confirm("确定删除该项目角色?", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      draggable: true,
    })
      .then(async () => {
        if (currentIndex.value === index) {
          //   删除当前项
          currentIndex.value = -1;
        }
        await deleteProjectRole(item.id!);
        ElMessage({
          type: "success",
          message: "删除成功",
        });
        getList();
      })
      .catch(() => {});
  };
  const handleAddRole = () => {
    operate.value = "create";
    dialogVisible.value = true;
  };
  const handleCreateOrEdit = async (formData: any) => {
    if (operate.value === "create") {
      const params: projectRoleVo = {
        projectId: props.projectId,
        name: {
          zh_CN: formData.name,
        },
        isManager: "NO",
      };
      await createProjectRole(params);
      ElMessage({
        type: "success",
        message: "添加成功",
      });
      dialogVisible.value = false;
      getList();
    } else if (operate.value === "edit") {
      const params: projectRoleVo = {
        id: formData.id,
        name: {
          zh_CN: formData.name,
        },
        projectId: props.projectId,
      };
      await editProjectRole(params);
      ElMessage({
        type: "success",
        message: "修改成功",
      });
      dialogVisible.value = false;
      getList();
    }
  };
  defineExpose({
    getList,
  });
  onMounted(() => {
    console.log(props.projectId, "projectId");
    getList();
  });
</script>

<style scoped lang="scss">
  .projectRoleListContainer {
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    padding: 12px 8px;
    border-right: 1px solid #e5e7eb;

    .text {
      color: #1d2129;
      font-weight: 600;
      font-size: 16px;
      line-height: 32px;
      padding: 0 12px;
      height: 32px;
    }
    .roleList {
      .roleItem {
        box-sizing: border-box;
        height: 36px;
        padding: 8px 12px;
        display: flex;
        border-radius: 4px;
        align-items: center;
        transition: all 0.2s;
        cursor: pointer;
        margin-bottom: 5px;
        &:hover {
          background: #e6f3fc;
        }
        .avatar {
          width: 20px;
          height: 20px;
          border-radius: 50%;
          margin-right: 8px;
        }
        .roleName {
          color: #1d2129;
          font-size: 13px;
          line-height: 22px;
          font-weight: 500;
          flex: 1;
        }
        .moreSpan {
          transition: all 0.2s;
          width: 24px;
          height: 24px;
          border-radius: 4px;
          display: flex;
          align-items: center;
          justify-content: center;
          &:hover {
            background: #d2dee6;
          }
        }
      }
    }
    .addItem {
      box-sizing: border-box;
      height: 36px;
      padding: 8px 12px;
      display: flex;
      border-radius: 4px;
      align-items: center;
      transition: all 0.2s;
      cursor: pointer;
      .addIcon {
        margin-right: 8px;
        width: 20px;
        height: 20px;
      }
    }
  }
</style>
<style lang="scss">
  .customPopoverClass {
    padding: 0 !important;
    width: 120px !important;
    min-width: 120px !important;
    .nodeMorePopoverClass {
      width: 128px;
      border: 1px solid #f2f2f2;
      padding: 4px;
      border-radius: 4px;
      box-shadow: 0 1px 8px 0 rgba(0, 0, 0, 0.16);
      background: #fff;
      .popoverList {
        padding: 0;
        margin: 0;
        list-style: none;
        .popoverItem {
          font-size: 14px;
          color: #2e405e;
          height: 32px;
          border-radius: 4px;
          background: #fff;
          transition: background-color 0.2s;
          cursor: pointer;
          display: flex;
          align-items: center;
          padding: 0 9px;
          &:hover {
            background: #f5f6f8;
          }
          img {
            width: 14px;
            height: 14px;
            margin-right: 9px;
          }
        }
      }
    }
  }
</style>
